

import ajax from './ajax'
import api from '../configs/api'

let isReady = false
let taskQueue = []

const config = () => {
    isReady = false
    const apiUrl = api.getURL('getWeixinSign')
    const query = {url: location.href.split('#l')[0]}
    ajax.getJSON(apiUrl, query).then((res) => {
        wx.config(Object.assign({
            debug: true,
            jsApiList: [
                'chooseWXPay',
                'openLocation',
                'getLocation'
            ]
        }, res))
    })
}

wx.ready(() => {
    isReady = true
    while (taskQueue.length > 0) {
        taskQueue.shift().call(null);
    }
})

const openLocation = (options) => {
    const wxAction = wx.openLocation

    if (isReady) {
        wxAction(options)
    } else {
        taskQueue.push(() => {
            wxAction(options)
        })
    }
}

const getLocation = (options) => {
    const wxAction = wx.getLocation

    if (isReady) {
        wxAction(options)
    } else {
        taskQueue.push(() => {
            wxAction(options)
        })
    }
}

const pay = (options) => {
    const wxAction = wx.chooseWXPay

    if (isReady) {
        wxAction(options)
    } else {
        taskQueue.push(() => {
            wxAction(options)
        })
    }
}

export default {
    openLocation,
    getLocation,
    pay
}
